package com.dage.salesflow.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.dage.salesflow.kit.Ret;
import com.dage.salesflow.model.Dict;
import com.dage.salesflow.service.DictService;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Kv;
import io.jboot.web.controller.annotation.RequestMapping;

import java.util.List;
import java.util.Map;

@RequestMapping("/dict")
public class DictController extends BaseController {
	@Inject
	DictService dictService;

	public void listByPage(String key, String value, Integer pid, int page, int limit) {
		renderPageJson(dictService.listByPage(key, value, pid, page, limit));
	}

	public void list(String key, String value, Integer pid) {
		List<Dict> list = dictService.list(key, value, pid);
		renderJson(Kv.by("code", 0).set("msg", "").set("count", list.size()).set("data", list));
	}

	public void listByKey(String key) {
		renderJson(Ret.ok(renderToString("/template/select-template.html", Kv.by("list", modelListToSelect(dictService.listByKey(key))))));
	}

	public void listDataByKey(String key) {
		renderJson(Ret.ok(dictService.listByKey(key)));
	}

	public void listByPid(int pid) {
		renderJson(Ret.ok(renderToString("/template/select-template.html", Kv.by("list", modelListToSelect(dictService.listByPid(pid))))));
	}

	public void listByKeys(String keys) {
		Map<String, List<Dict>> map = dictService.listByKeys(keys);
		Kv kv = Kv.create();
		for (Map.Entry<String, List<Dict>> entry : map.entrySet()) {
			String list = renderToString("/template/select-template.html", Kv.by("list", modelListToSelect(entry.getValue())));
			kv.put(entry.getKey(), list);
		}
		renderJson(Ret.ok(kv));
	}

	public void add() {
		StpUtil.checkRole("role1");
		if (dictService.save(getBean(Dict.class, "")) != null) {
			renderJson(Ret.ok());
		} else {
			renderJson(Ret.err("添加失败"));
		}
	}

	public void update() {
		StpUtil.checkRole("role1");
		if (dictService.update(getBean(Dict.class, ""))) {
			renderJson(Ret.ok());
		} else {
			renderJson(Ret.err("修改失败"));
		}
	}

	public void del(int id) {
		StpUtil.checkRole("role1");
		renderJson(dictService.del(id));
	}

}
